package com.charles.seckillsystem.schedule;

import com.charles.seckillapi.domain.SysGood;
import com.charles.seckillcommon.core.constants.CacheConstants;
import com.charles.seckillcommon.core.utils.SpringUtils;
import com.charles.seckillcommon.redis.service.RedisService;
import com.charles.seckillsystem.mapper.SysGoodMapper;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.util.Date;
import java.util.List;

/**
 * @author Charles-H
 * 
 * 每日定时任务
 */
public class DailyJob implements Job {

    /**
     * 每天对产品的存取操作
     *
     * @param jobExecutionContext
     * @throws JobExecutionException
     */
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        // 因为Quartz不支持bean注入，所以需要实例化对象
        SysGoodMapper sysGoodMapper = SpringUtils.getBean(SysGoodMapper.class);
        RedisService redisService = SpringUtils.getBean(RedisService.class);

        // 将数据库中秒杀开始时间小于24小时的产品存入Redis缓存中
        // 将Redis缓存中秒杀结束的产品存入数据库中
        List<SysGood> goodList = sysGoodMapper.queryGoodList();
        for (SysGood good : goodList) {
            Date now = new Date();
            if ((now.getTime() - good.getStart_time().getTime()) <= 86400000 
                    && redisService.getCacheObject(CacheConstants.GOOD_ID + good.getGood_id()) == null
                    && now.before(good.getEnd_time())) {
                redisService.setCacheObject(CacheConstants.GOOD_ID + good.getGood_id(), good);
            }

            if (now.after(good.getEnd_time())) {
                SysGood goodRedis = (SysGood) redisService.getCacheObject(CacheConstants.GOOD_ID + good.getGood_id());
                if (goodRedis != good && goodRedis != null) {
                    sysGoodMapper.saveGood(goodRedis);
                }
            }

        }

    }

}
